﻿using MemorySiteServer.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using BaseAPI;

namespace MemorySiteServer.Models
{
    public class UserAudience : BaseEntity
    {
        public long UserID { get; set; }
        /// <summary>
        /// 用户信息直接缓存到内存，加速授权流程
        /// </summary>
        public virtual User User { get; set; }
        /// <summary>
        /// 服务器端记录的订阅者（在用户登录时记录）
        /// </summary>
        public string ServerAudience { get; set; }

        /// <summary>
        /// 赋值UserID,User和ServerAudience
        /// </summary>
        /// <param name="user"></param>
        public void Init(User user)
        {
            UserID = user.ID;
            User = user;
            ServerAudience = Guid.NewGuid().ToString();
        }

        public async Task AddUserAudience(DbContext dataContext)
        {
            var dbUserAudience = Clone();
            dbUserAudience.User = null;
            dataContext.Set<UserAudience>().Add(dbUserAudience);
            await dataContext.SaveChangesAsync();
            ID = dbUserAudience.ID;
        }

        public async Task UpdataUserAudience(DbContext dataContext)
        {
            var dbUserAudience = this.Clone();
            dbUserAudience.User = null;
            dataContext.Set<UserAudience>().Attach(dbUserAudience);
            dataContext.Entry(dbUserAudience).Property(x => x.ServerAudience).IsModified = true;
            await dataContext.SaveChangesAsync();
        }

        public UserAudience Clone()
        {
            return MemberwiseClone() as UserAudience;
        }

        public void SetNewServerAudienceValue()
        {
            ServerAudience = Guid.NewGuid().ToString();
        }

        public static List<UserAudience> GetUserAudienceList(DbContext dataContext)
        {
            return dataContext.Set<UserAudience>().AsNoTracking().Include(x => x.User)
                .ThenInclude(x => x.Role).ThenInclude(x => x.RolePermissions).ToList();
        }
    }
}
